package com.haiheng.voiceandbook

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.haiheng.voiceandbook.utils.SpUtil

/**
 *
 * @Des:防止第三方输入法退出
 * @Author: hwz
 * @Date:2023/3/17 0017
 * @Version: 1.0
 */
class AppForegroundListener : Application.ActivityLifecycleCallbacks {
    public var appInForeground = false
    private val handler = Handler(Looper.getMainLooper())
    private var activityCount = 0

    override fun onActivityResumed(activity: Activity) {
        Log.e("AppForegroundListener","onActivityResumed packageName :${activity.packageName} componentName:${activity.componentName}")
        appInForeground = true
        if (activityCount == 0) {
            // 应用进入前台
            Log.e("AppForegroundListener","应用进入前台")
        }
        activityCount++
        SpUtil.putBoolean(MyApplication.getInstance(),Constants.SP_IS_APP_IN_FOREGROUND,true)

    }

    override fun onActivityPaused(activity: Activity) {
        activityCount--
        if (activityCount == 0) {
            Log.e("AppForegroundListener","应用进入后台")
            // 应用进入后台
            SpUtil.putBoolean(MyApplication.getInstance(),Constants.SP_IS_APP_IN_FOREGROUND,false)
        }
        Log.e("AppForegroundListener","onActivityPaused packageName :${activity.packageName} componentName:${activity.componentName} activityCount:${activityCount}")

        // 应用切换到后台的逻辑处理 ,是否退出后重新启动
        if (Constants.isExitOpenApp()){
            appInForeground = false
            handler.postDelayed({
                Log.e("AppForegroundListener","延迟1s后的状态：$appInForeground  isExt: ${Constants.isExitOpenApp()}")
                if (!appInForeground){
                    val intent = Intent(MyApplication.getInstance().applicationContext, MainActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    MyApplication.getInstance().applicationContext.startActivity(intent)
                }
            },1200)
        }

    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        appInForeground = true
        Log.e("AppForegroundListener","onActivityCreated packageName :${activity.packageName} componentName:${activity.componentName}")

    }

    override fun onActivityStarted(activity: Activity) {
        Log.e("AppForegroundListener","onActivityStarted activity :${activity.packageName} activityCount:${activityCount}")

        appInForeground = true
    }

    override fun onActivityStopped(activity: Activity) {
        Log.e("AppForegroundListener","onActivityStopped componentName:${activity.componentName}")

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {}

    fun isAppInForeground(): Boolean {
        return activityCount > 0
    }
}
